public with sharing class ShiyeApplicationGoodDetailCreated {

    public void  test(){

    }
    /*public List<SelectOption> products {set;get;}//可选产品;
    public List<SelectOption> serialNos {set;get;}//货号
    public List<SelectOption> brands {set;get;}//品牌
    public List<SelectOption> categorys {set;get;}// 一级分类
    
    public List<ShiyeApplicationGoodDetailBean> ds {set;get;}//合同产品;
    public Map<Id,ShiyeApplicationGoodDetailBean> originds {set;get;}//合同产品;

    public String company {set;get;} //当前用户的公司
    public String sId {set;get;}//实业借货Id;
    public ShiyeApplicationGoods__c currentSg  {set;get;}//当前实业借货申请;
   // public Id accId ;//当前实业借货申请的客户;
    
    public String product {set;get;}//可选产品;
    public String serialNo {set;get;}//货号
    public String brand {set;get;}//品牌
    public String category {set;get;}// 一级分类 
    
    public Boolean isSuccess {get;private set;}//是否操作成功
    public ShiyeApplicationGoodDetailCreated(ApexPages.StandardController con){
    company = [select SubCompany__c from User where Id = :System.UserInfo.getUserId()].SubCompany__c;
        sId = System.currentPageReference().getParameters().get('id');
        currentSg = [select Customer__c,Customer__r.Name  from ShiyeApplicationGoods__c where id =:sId];
        ds = new List<ShiyeApplicationGoodDetailBean>();
        originds = new Map<Id,ShiyeApplicationGoodDetailBean>();
        isSuccess = false;
    }
    public void init(){
        
        ///找到满足条件的合同
            Set<Id> cIds = new Set<Id>();
    if(currentSg.Customer__c != null){
        for(Contract__c c : [select Id ,CompanyControls__c from Contract__c where
                                  CompanyControls__c =: company and ManualImport__c = true and 
                               Status__c ='已生效' and Account__c =:currentSg.Customer__c]){
                cIds.add(c.Id);
            }

        }
        Map<Id,String>cp_com = new Map<Id ,String>();

        Set<Id>proIds = new Set<Id>();
         ///如果公司和产品为空的时候可能有问题 
        Map<String ,ContractProduct__c>cps = new Map<String,ContractProduct__c>();
        /// 找到对应的合同产品
       List<ContractProduct__c> cpsOrgin = [select Id ,Product__r.Name, Type__c,Product__r.SerialNo__c,
               Product__r.Brand__c,Product__r.Category1__c,Product__r.Spec__c,Product__r.Model__c,
               Contract__r.CompanyControls__c,Product__r.ProductLineName__c,Product__c,SalesPrice__c  
               from ContractProduct__c where Contract__c in : cIds];
        for(ContractProduct__c cp: cpsOrgin){
        	cps.put(cp.Contract__r.CompanyControls__c + cp.Product__c,cp);
            proIds.add(cp.Product__c);
            cp_com.put(cp.Id,cp.Contract__r.CompanyControls__c + cp.Product__c);

        }
     

       
        ///公司低价(元) 应调整价格(元)
        Map<Id ,Price__c> cp_prs = new Map<Id,Price__c>();
        for (Price__c p : [select Product__c,Company__c,CompanyBottomPrice__c,HospitalBottomPrice__c
                           from Price__c where Product__c in: proIds]){
           for(Id key : cp_com.keySet()){
           		if(cp_com.get(key) == p.Company__c + p.Product__c ){
                     cp_prs.put(key,p);  
                }
           }
        }
        /// 日期处理
        Integer m = Date.today().month(); //当前月份
        Integer y = Date.today().year();  //当前年份 
       ///取上月
         if(m == 1){
        m = 12 ;
            y -= 1;
        }else{
        m -= 1;
            
        }
        
        String  month = String.valueOf(m) + '月';
        String  year= String.valueOf(y) + '年';
        //上月平均价(元)
         Map<Id ,AveragePrice__c>lastPs = new Map<Id ,AveragePrice__c>();
         for(AveragePrice__c a : [select AveragePrice__c  ,Product__c,Company__c from AveragePrice__c where 
                                  Year__c =:year and Month__c =: month and Product__c in : proIds]){
            for(Id key : cp_com.keySet()){
           		if(cp_com.get(key) == a.Company__c + a.Product__c ){
                     lastPs.put(key,a);  
                }
           }
         }
        
         //挂网流水号
         Map<Id,NetSerialNumber__c> nets = new Map<Id ,NetSerialNumber__c>();
         for (NetSerialNumber__c n : [select NetSerialNumber__c ,Product__c,Company__c 
                                      from NetSerialNumber__c where Product__c in : proIds]){
            for(Id key : cp_com.keySet()){
           		if(cp_com.get(key) == n.Company__c + n.Product__c ){
                     nets.put(key,n);  
                }
           }
         }
        
        
        Set<String> ps = new Set<String>();
        Set<String> ss = new Set<String>();
        Set<String> bs = new Set<String>();
        Set<String> cas = new Set<String>();
        for(ContractProduct__c cp: cpsOrgin){
            if(cp.Product__r.Name != null)ps.add(cp.Product__r.Name);
 
            if(cp.Product__r.SerialNo__c != null)ss.add(cp.Product__r.SerialNo__c);
            if(cp.Product__r.Brand__c != null)bs.add(cp.Product__r.Brand__c);
            if(cp.Product__r.Category1__c != null)cas.add(cp.Product__r.Category1__c);
            
            ShiyeApplicationGoodDetailBean d = new ShiyeApplicationGoodDetailBean();
            d.productName = cp.Product__r.Name;
            d.size = cp.Product__r.Spec__c;
            d.model = cp.Product__r.Model__c;
            d.brand = cp.Product__r.Brand__c;
            d.productLine = cp.Product__r.ProductLineName__c;
            d.price = cp.SalesPrice__c == null ? 0.0 : cp.SalesPrice__c;
            
            d.cp = cp;
            d.category = cp.Product__r.Category1__c;
            d.serialNo = cp.Product__r.SerialNo__c;
            d.type = cp.Type__c;
       		 if(cp_prs.containsKey(cp.Id)){
                Price__c p = cp_prs.get(cp.Id);
            	d.companyPrice = p.CompanyBottomPrice__c;
             	d.priceAdjustment= p.HospitalBottomPrice__c;
            }
            if(lastPs.containsKey(cp.Id)){
                AveragePrice__c a = lastPs.get(cp.Id);
           		d.averagePriceLastMonth = a.AveragePrice__c;
            }
            if(nets.containsKey(cp.Id)){
                NetSerialNumber__c n = nets.get(cp.Id);
            	d.netSerialNumber = n.NetSerialNumber__c;
            }
            //差异率
            if(d.priceAdjustment != null && d.priceAdjustment !=0){
                System.debug(d.priceAdjustment + ' ' + d.price);
             d.salesPriceVariance =((d.priceAdjustment - d.price )/d.priceAdjustment * 100 ).format()+'%';
            }
            System.debug(d.priceAdjustment + ' ' + d.price);

            
            ds.add(d);
            originds.put(cp.Id,d);
            
        }
        
        System.debug('产品'+ ps);
        ///选项列表按钮处理
        products = optionHandler(ps);
        serialNos = optionHandler(ss);
        brands = optionHandler(bs);
        categorys = optionHandler(cas);
        
        
     }
    public void save(){
        SavePoint sp = Database.setSavePoint();
        try{
            List<ShiyeApplicationGoodsDetails__c> rs = new List<ShiyeApplicationGoodsDetails__c>();
            Boolean flag = false;
            for(ShiyeApplicationGoodDetailBean s : ds){
                if(s.isChecked == true){
                    if( s.productLine == null) {
                    	flag = true;
                        break;
                    }
                   ShiyeApplicationGoodsDetails__c r = new ShiyeApplicationGoodsDetails__c();
                    r.ShiyeApplicationGoods__c = sId;
                    r.AveragePriceLastMonth__c = s.averagePriceLastMonth;
                    r.Product__c = s.cp.Id;
                    r.OrderQuantity__c = s.OrderQuantity;
                    r.CompanyPrice__c = s.companyPrice;
                    r.NetSerialNumber__c = s.netSerialNumber;
                    r.PriceAdjustment__c = s.priceAdjustment;
                    
                    r.ProductLine__c = s.productLine;

                 rs.add(r);
                 System.debug('数据:'+r);
               }
           }
           if(flag){
               isSuccess = false;

              ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,
                                    '不能保存! 存在产品线为空的产品! 提示需联系市场部维护产品结构!'));
           }else{
             insert rs;
            isSuccess = true;
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,
                                     'OK'));
           }

        }catch(Exception e){
            Database.rollback(sp);
             ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,
                                    '操作出错：'+e.getMessage()));
        }

    }

    public void search(){
      List<ContractProduct__c> temp = new list<ContractProduct__c>();

      ds = new List<ShiyeApplicationGoodDetailBean>();
       Schema.DescribeSobjectResult m = ContractProduct__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();
        String sql = 'select ';
        String fields = '';
        for (String field : fieldMap.keySet()) {
            if (fields.length() > 0) {
                fields += ', '; 
            }
            fields += field;
        }
        sql += fields;
        sql += ' from ContractProduct__c where Contract__r.Account__c = \'' + currentSg.Customer__c + '\'';
       String whereStr = '';
        if (String.isBlank(product) == false) {
            whereStr += ' and Product__r.Name like \'%' + product + '%\'';
        }
        if (String.isBlank(brand) == false) {
            whereStr += ' and  Product__r.Brand__c like \'%' + brand + '%\'';
        }
        if (String.isBlank(serialNo) == false) {
            whereStr += ' and  Product__r.SerialNo__c like \'%' + serialNo + '%\'';
        }
         if (String.isBlank(category) == false) {
            whereStr += ' and  Product__r.Category1__c like \'%' + category + '%\'';
        }
       temp = Database.query(sql + whereStr + ' limit 500');
        for(ContractProduct__c cp : temp){
            if(originds.containsKey(cp.Id)){
                ds.add(originds.get(cp.Id));
            }
        }
        
   }
    private List<SelectOption>  optionHandler (Set<String> s){
    List<SelectOption> ss = new List<SelectOption>();
       ss.add(new SelectOption('', System.Label.Option_None));

        for (String str : s){
        ss.add(new SelectOption(str,str));
        }
        return ss;
    }
    public class ShiyeApplicationGoodDetailBean{
    public ContractProduct__c cp {get;set;}
        public String type {get;set;}//产品类型
        public Boolean isChecked {get;set;} // 将要保存的数据项
        public Decimal price {get;set;}//医院现供货价
        public String code {get;set;}//存货代码
        public String productLine {get;set;}// 产品线
        public String brand {get;set;}//品牌
        public Decimal OrderQuantity {get;set;}//订货数量
        public String netSerialNumber {get;set;}//挂网流水号
        public String size {get;set;}//规格
        public Decimal averagePriceLastMonth {get;set;} //上月平均价
        public Decimal priceAdjustment {get;set;}//应调整价格
        public String salesPriceVariance {get;set;}///差异率(对比销售员低价)
        public String productName {get;set;}//存货名称
        public String model {get;set;} //型号;
        public Decimal companyPrice {get;set;}//公司低价
        //public Decimal ShiyeApplicationGoods {get;set;}//实业借货申请
        
        public String category {get;set;}//一级分类
        public String serialNo  {get;set;}//货号
    } 
    */
}